package com.yjj.springboot3.utils;

import cn.hutool.core.io.FileUtil;
import com.yjj.springboot3.config.FileConfig;
import com.yjj.springboot3.exception.BusinessException;
import com.yjj.springboot3.common.ErrorCode;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传工具类
 *
 * @author yjj
 */
@Slf4j
@Component
public class FileUploadUtils {

    @Resource
    private FileConfig fileConfig;

    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024L;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认允许的扩展名
     */
    public static final List<String> DEFAULT_ALLOWED_EXTENSION = Arrays.asList(
            "bmp", "gif", "jpg", "jpeg", "png",
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
            "rar", "zip", "gz", "bz2",
            "mp4", "avi", "rmvb", "mkv",
            "pdf"
    );

    /**
     * 图片扩展名
     */
    public static final List<String> IMAGE_EXTENSION = Arrays.asList("bmp", "gif", "jpg", "jpeg", "png");

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件访问路径
     */
    public String upload(MultipartFile file) throws IOException {
        return upload(fileConfig.getUploadPath(), file, DEFAULT_ALLOWED_EXTENSION);
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件访问路径
     */
    public String upload(String baseDir, MultipartFile file) throws IOException {
        return upload(baseDir, file, DEFAULT_ALLOWED_EXTENSION);
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件访问路径
     */
    public String upload(String baseDir, MultipartFile file, List<String> allowedExtension) throws IOException {
        int fileNameLength = file.getOriginalFilename().length();
        if (fileNameLength > DEFAULT_FILE_NAME_LENGTH) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件名过长");
        }

        assertAllowed(file, allowedExtension);

        String fileName = extractFilename(file);
        String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        return getPathFileName(baseDir, fileName);
    }

    /**
     * 编码文件名(日期格式目录 + UUID + 后缀)
     */
    public String extractFilename(MultipartFile file) {
        String extension = getExtension(file);
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return String.format("%s/%s.%s", datePath, uuid, extension);
    }

    /**
     * 获取文件绝对路径
     */
    private File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    /**
     * 获取文件访问路径
     */
    private String getPathFileName(String uploadDir, String fileName) {
        int dirLastIndex = fileConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        return fileConfig.getResourcePrefix() + "/" + currentDir + "/" + fileName;
    }

    /**
     * 文件大小校验
     *
     * @param file             上传的文件
     * @param allowedExtension 允许的扩展名
     */
    public void assertAllowed(MultipartFile file, List<String> allowedExtension) {
        long size = file.getSize();
        if (size > DEFAULT_MAX_SIZE) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小超出限制");
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !allowedExtension.isEmpty() && !allowedExtension.contains(extension)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式不允许");
        }
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public String getExtension(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String extension = filename.substring(filename.lastIndexOf(".") + 1);
        if (StringUtils.isEmpty(extension)) {
            extension = getExtensionByMimeType(file.getContentType());
        }
        return extension;
    }

    /**
     * 根据MIME类型获取扩展名
     */
    private String getExtensionByMimeType(String mimeType) {
        String extension = "";
        if ("image/jpeg".equals(mimeType)) {
            extension = "jpg";
        } else if ("image/gif".equals(mimeType)) {
            extension = "gif";
        } else if ("image/png".equals(mimeType)) {
            extension = "png";
        }
        return extension;
    }
}
